package com.example.service.impl;

import com.example.entity.Device;
import com.example.entity.UserDevice;
import com.example.mapper.DeviceMapper;
import com.example.mapper.UserDeviceMapper;
import com.example.service.UserDeviceService;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserDeviceServiceImpl implements UserDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private UserDeviceMapper userDeviceMapper;
    private static final Snowflake snowflake = IdUtil.getSnowflake(1, 1);

    @Override
    public boolean bindDevice(Long userId, String sn) {
        Device device = deviceMapper.findBySn(sn);
        if (device == null) throw new RuntimeException("设备不存在");
        UserDevice exist = userDeviceMapper.findByUserIdAndDeviceId(userId, device.getId());
        if (exist != null) throw new RuntimeException("已绑定该设备");
        UserDevice userDevice = new UserDevice();
        userDevice.setId(snowflake.nextId());
        userDevice.setUserId(userId);
        userDevice.setDeviceId(device.getId());
        userDevice.setIsOwner(true);
        userDevice.setIsCurrent(true);
        userDevice.setCreatedTime(new Date());
        userDevice.setCurrentDeviceRoleId(null);
        userDeviceMapper.insert(userDevice);
        return true;
    }
} 